<template>
	<div>
		<div class="util">
		  <span>
		  	<Complaint style="width:30px;"/>
		  </span>
		  <el-tag>投诉统计</el-tag>
		  <el-tag>投诉处理</el-tag>
		  <el-input type="text"
		  placeholder="请输入投诉类型" 
		  v-model="input"
		  style="width: 200px;height: 35px;margin-top: 20px;
		  margin-bottom: 20px;margin-right: 0px;margin-left: 60%;"/>
		  <el-button :icon="Search" 
		  style="margin-left: 5px;margin-bottom: 8px;" 
		  circle
		   @click="search" />
		</div>
		<div class="main">
			<div class="main1">
				<div style="display: flex; height: 100%;">
				        <div style="flex: 2; height: 100%;">
				          <h3 style="margin-left: 20px; margin-bottom: 10px;">每日投诉量统计</h3>
				          <div ref="barChart" style="width: 100%; height: 250px;"></div>
				        </div>
				        <div style="flex: 2; height: 100%; margin-left: 20px;">
				          <h3 style="margin-left: 20px; margin-bottom: 10px;">投诉类型分布</h3>
				          <div ref="pieChart" style="width: 100%; height: 250px;"></div>
				        </div>
				      </div>
			</div>
			
			
			<el-table
			:data="tableData.records" 
			:model="tousu"
			:header-cell-style="{background:'#F3F4F7',color:'#555',}"
			style="width: 100%;"
			height="400">
					<el-table-column v-model="tousu.type" label="投诉类型" prop="type" align="center" width="auto" />
					<el-table-column v-model="tousu.createTime" label="提交时间" prop="createTime" align="center" width="210px" />
					<el-table-column label="内容描述" prop="content" align="center" width="auto">
						<template #default="scope">
						    <el-popover effect="light" trigger="hover" placement="top" width="auto">
						        <template #default>
						            <div>{{ scope.row. content}}</div>
						        </template>
								<template #reference >
								  <el-tag>详情查看</el-tag>
								</template>
							</el-popover>
						</template>
					</el-table-column>
					<el-table-column property="status"  label="状态" align="center"  width="150px">
						<template #default="scope">
							<el-tag type="warning" v-if="scope.row.status==0">未审核</el-tag>
							<el-tag type="success" v-if="scope.row.status==1">已处理</el-tag>
							<el-tag type="danger" v-if="scope.row.status==2">已驳回</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="180px">
					  <template #default="scope">
						  <template v-if="scope.row.status==0">
							  <el-button
							  size="small" 
							  type="success" 
							  @click="pass(scope.row.id,scope.row.status,1)"
							  plain>
							    通过
							  </el-button>
							  <el-button
							    size="small"
							    type="danger"
							    plain
							    @click="reject(scope.row.id,scope.row.status,2)">
							    驳回
							  </el-button>
						  </template>
						  <el-button v-else type="warning" 
						  plain size="small"
						  @click="reject(scope.row.id,scope.row.status,0)">
						  重新处理</el-button>
					  </template>
					</el-table-column>
			</el-table>
			<el-pagination
						background
						:page-count="tableData.pages"
						v-model:current-page="params.page"
						:total="tableData.total"
						:close-on-click-modal="false"
						@current-change="getTableData()"
						style="margin-top:15px;"></el-pagination>
		</div>
		
	</div>
</template>

<script lang="ts" setup>
import Complaint from  '@/components/icons/CommunityIcon/complaint'
import Search from '@/components/icons/CommunityIcon/Search'
import { ref, reactive ,onMounted, nextTick} from 'vue'
import { ElMessage,ElMessageBox ,ElTable} from 'element-plus'
import {_axios,post,get} from '@/plugins/axios'
import url from './util'
import * as echarts from 'echarts'

const input = ref('')
const formObj = null
const tableData = reactive({
	  records: [] ,// 初始化为空数组
	  pages: 0,
	  total: 0
	});
	const params = reactive({
	    page: 1,
	    limit: 6
	})
// 图表相关变量
const barChart = ref(null)
const pieChart = ref(null)
let barChartInstance = null
let pieChartInstance = null


// 新增统计相关变量
const statsData = reactive({
  dailyVisitors: [] as Array<{date: string, count: number}>,
  visitorTypes: [] as Array<{type: string, count: number}>
})

// 初始化图表
function initCharts() {
  barChartInstance = echarts.init(barChart.value)
  pieChartInstance = echarts.init(pieChart.value)
  
  // 柱状图配置
  const barOption = {
    title: {
      text: '每日投诉量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0].data
        return `日期: ${params[0].axisValue}<br/>投诉量: ${data}条`
      }
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '投诉量(条)'
    },
    series: [{
      name: '投诉量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#36a3f7'
      }
    }],
    graphic: {
      type: 'text',
      left: 'center',
      top: 'middle',
      style: {
        text: '正在加载数据...',
        fill: '#999',
        fontSize: 16
      }
    }
  }

  // 饼图配置
  const pieOption = {
    title: {
      text: '投诉类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [{
      name: '投诉类型',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [],
      label: {
        show: true,
        formatter: '{b}: {c}人'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }],
    graphic: {
      type: 'text',
      left: 'center',
      top: 'middle',
      style: {
        text: '正在加载数据...',
        fill: '#999',
        fontSize: 16
      }
    }
  }

  barChartInstance.setOption(barOption)
  pieChartInstance.setOption(pieOption)
}

// 计算统计数据
function calculateStats() {
  // 1. 计算每日投诉量
  const dailyMap = new Map<string, number>()
  
  tableData.records.forEach(record => {
    // 处理日期格式 (只取年月日部分)
    const date = record.createTime ? record.createTime.split(' ')[0] : '未知日期'
    const count = record.count || 1 // 默认每个记录算1
    
    if (dailyMap.has(date)) {
      dailyMap.set(date, dailyMap.get(date)! + count)
    } else {
      dailyMap.set(date, count)
    }
  })
  
  // 转换为数组并排序
  statsData.dailyVisitors = Array.from(dailyMap.entries())
    .map(([date, count]) => ({ date, count }))
    .sort((a, b) => a.date.localeCompare(b.date))

  // 2. 计算投诉类型分布
  const typeMap = new Map<string, number>()
  
  tableData.records.forEach(record => {
    const type = record.type || '未知类型'
    const count = record.count || 1
    
    if (typeMap.has(type)) {
      typeMap.set(type, typeMap.get(type)! + count)
    } else {
      typeMap.set(type, count)
    }
  })
  
  statsData.visitorTypes = Array.from(typeMap.entries())
    .map(([type, count]) => ({ type, count }))
    .sort((a, b) => b.count - a.count) // 按数量降序

  // 3. 更新图表
  updateCharts()
}

// 更新图表数据
function updateCharts() {
  if (!barChartInstance || !pieChartInstance) return

  // 更新柱状图
  barChartInstance.setOption({
    xAxis: {
      data: statsData.dailyVisitors.map(item => item.date)
    },
    series: [{
      data: statsData.dailyVisitors.map(item => item.count)
    }],
    graphic: {
      invisible: statsData.dailyVisitors.length > 0
    }
  })

  // 更新饼图
  pieChartInstance.setOption({
    legend: {
      data: statsData.visitorTypes.map(item => item.type)
    },
    series: [{
      data: statsData.visitorTypes.map(item => ({
        name: item.type,
        value: item.count
      }))
    }],
    graphic: {
      invisible: statsData.visitorTypes.length > 0
    }
  })

  // 无数据提示
  if (statsData.dailyVisitors.length === 0) {
    barChartInstance.setOption({
      graphic: {
        style: {
          text: '暂无投诉数据'
        }
      }
    })
  }

  if (statsData.visitorTypes.length === 0) {
    pieChartInstance.setOption({
      graphic: {
        style: {
          text: '暂无投诉类型数据'
        }
      }
    })
  }
}

// 修改getTableData3函数
function getTableData3() {
	get('/complaint/list1',null,content => {
	  tableData.records = content//不需要content.records作分页
    // 数据加载完成后计算统计
    calculateStats()
  })
}

// 组件挂载时初始化
onMounted(() => {
  initCharts()
  getTableData3()
})





getTableData()
function getTableData(){
	post('/complaint/list2',{pageNo:params.page, pageSize:params.limit },content=>{
			tableData.records = content.records
		    tableData.pages = content.pages
		    tableData.total = content.total			
			})
	}
const tousu=reactive({
	id:null,
	type:'',
	content:'',
	userId:'',
	createTime:'',
	status:''
})

const pass = (id,status,statu) =>  {
	console.dir(status)
	let text=''
	if(status==0){text='确定处理该投诉吗？'}
	else{text='投诉已处理'}
	 	ElMessageBox.confirm(
	 	   text,'提示',
	 	    {
	 	      confirmButtonText: '确定',
	 	      cancelButtonText: '取消',
	 	      type: 'warning',
	 	    }
	 	  ).then(() => {
			  post(url.pass, { id,status,statu }, content => {
			  	getTableData()
			  },formObj)
	 	    }).catch(() => {
	 	      ElMessage({
	 	        type: 'info',
	 	        message: '已取消，请尽快处理',
	 	      })
	 	    })
	 }
const reject = (id,status,statu) =>  {
	 	console.dir(status)
	 	let text=''
	 	if(status==0){text='确定驳回该投诉吗？'}
		else if(status==2||status==1){text='确定重新处理该投诉吗？'}
	 	else{text='投诉已处理'}
	 	 	ElMessageBox.confirm(
	 	 	   text,'提示',
	 	 	    {
	 	 	      confirmButtonText: '确定',
	 	 	      cancelButtonText: '取消',
	 	 	      type: 'warning',
	 	 	    }
	 	 	  ).then(() => {
	 			  post(url.reject, { id,status,statu }, content => {
	 			  	getTableData()
	 			  },formObj)
	 	 	    }).catch(() => {
	 	 	      ElMessage({
	 	 	        type: 'info',
	 	 	        message: '已取消，请尽快处理',
	 	 	      })
	 	 	    })
	 	 }
 
const search=()=>{
 	console.dir(input.value)
 	post(url.search, {input:input.value,pageNo:params.page, pageSize:params.limit}, content => {
		tableData.records=content.records
		console.dir(tableData.records)
 	},formObj)
}

</script>

<style scoped>
	.el-button{
		margin-top: 10px;
		margin-left: 5%;
	}
#barChart, #pieChart {
  background: #fff;
  border-radius: 4px;
  transition: all 0.3s;
}

.el-tag {
  margin-right: 10px;
  cursor: pointer;
}
.util{
  width: 100%;
  height: 60px;
  background-color: #ffffff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  .add-button{
    margin-left: 20px;
    margin-right: 809px;
  }
  span{
    font-size: 14px;
    margin-left: 20px;
  }
}
.main{
  width: 100%;
  padding: 15px;
  /*height: 580px;*/
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 2px 0px 10px rgba(0,0,0,0.2);
  overflow: hidden;
}
.main1 {
  width: 100%;
  padding: 15px;
  background-color: #ffffff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 2px 0px 10px rgba(0,0,0,0.2);
}
.main2 {
  width: 100%;
  padding: 15px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 2px 0px 10px rgba(0,0,0,0.2);
}
</style>